import StringTool from "./StringTool";
export default class ResourcesTool {
    /**
     * 加载网路图片
     * @param replaceSprite 精灵
     * @param url 图片链接
     * @param callBack 回调
     * @returns 
     */
    public static LoadImageByUrl(replaceSprite: cc.Sprite, url: string, callBack: Function = null): boolean {
        if (!replaceSprite || StringTool.IsEmpty(url)) {
            if (callBack)
                callBack(false);
            return false;
        }

        cc.loader.load(url, function (err: boolean, texture: cc.Texture2D) {
            let result: boolean = false;
            if (err || !texture || !cc.isValid(replaceSprite)) {
                result = false;
            }
            else {
                let spf = new cc.SpriteFrame(texture);
                replaceSprite.spriteFrame = spf;
                result = true;
            }
            if (callBack)
                callBack(result);
        });
        return true;
    }

    /**
     * 加载resourse内资源
     * @param sprite 精灵
     * @param path 路径
     * @param callBack 回调
     * @returns 
     */
    public static LoadImage(sprite: cc.Sprite, path: string, callBack: Function = null): boolean {
        if (!sprite || !path) {
            if (callBack)
                callBack(false);
            return false;
        }
        cc.loader.loadRes(path, cc.SpriteFrame, function (err, spriteFrame) {
            let rsult: boolean = false;
            if (err || !cc.isValid(sprite) || !spriteFrame) {
                rsult = false;
            }
            else {
                sprite.spriteFrame = spriteFrame;
                rsult = true;
            }
            if (callBack)
                callBack(rsult);
        });
        return true;
    }

    /**
     * 加载组图内的资源
     * @param sprite 精灵
     * @param path 图集路径
     * @param name 图片名字
     * @param callBack 回调
     * @returns 
     */
    public static loadImageAtlas(sprite: cc.Sprite, path: string, name: string, callBack: Function = null): boolean {
        if (!sprite || !path || !name) {
            if (callBack)
                callBack(false);
            return false;
        }
        cc.loader.loadRes(path, cc.SpriteAtlas, function (err, atlas: cc.SpriteAtlas) {
            let rsult: boolean = false;
            if (err || !cc.isValid(sprite) || !atlas) {
                rsult = false;
            }
            else {
                let spriteFrame = atlas.getSpriteFrame(name);
                if (!spriteFrame)
                    rsult = false;
                else {
                    sprite.spriteFrame = spriteFrame;
                    rsult = true;
                }
            }
            if (callBack)
                callBack(rsult);
        });
        return true;
    };
}